package com.citycloud.ccuap.tc.admin.projectapp;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.curator.shaded.com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.citycloud.ccuap.framework.exception.ApplicationException;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.framework.mybatis.pagination.Pagination;
import com.citycloud.ccuap.framework.service.mybatis.MybatisServiceImpl;
import com.citycloud.ccuap.tc.admin.dto.SysAppDto;
import com.citycloud.ccuap.tc.admin.entity.OauthClientDetails;
import com.citycloud.ccuap.tc.admin.entity.SysApp;
import com.citycloud.ccuap.tc.admin.repository.OauthClientDetailsRepository;
import com.citycloud.ccuap.tc.admin.repository.SysAppRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SysAppServiceImpl extends MybatisServiceImpl<SysAppRepository, SysApp, String> implements SysAppService {
    @Autowired
    private SysAppRepository sysAppRepository;
    
    @Autowired
    @Lazy
    private SysAppMapper sysAppMapper;
    
    @Autowired
    private OauthClientDetailsRepository oauthClientDetailsRepository;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public SysAppVO getSysAppDetail(String clientId) {
        SysApp sysApp = sysAppRepository.findByClientIdOrderByAppIdDesc(clientId);
        OauthClientDetails oauthClientDetails = oauthClientDetailsRepository.findByClientId(sysApp.getClientId());
        if (null == oauthClientDetails) {
            throw new ApplicationException(401, "ClientId未注册");
        }
        log.info("sysApp:{},oauthClientDetails:{}", sysApp, oauthClientDetails);
        return SysAppVO.builder()
                .appDescribe(sysApp.getAppDescribe())
                .appLogo(sysApp.getAppLogo())
                .appName(sysApp.getAppName())
                .appType(sysApp.getAppType())
                .appId(sysApp.getAppId())
                .clientId(sysApp.getClientId())
                .webServerRedirectUri(oauthClientDetails.getWebServerRedirectUri())
                .clientSecret(oauthClientDetails.getClientSecret())
                .secret(oauthClientDetails.getSecret())
                .resource(oauthClientDetails.getResourceIds())
                .authorizedGrantTypes(Arrays.asList(oauthClientDetails.getAuthorizedGrantTypes().split(",")))
                .build();
    }

    @Override
    public PageQuery<Map<String, Object>> querySysAppPage(PageQuery<Map<String, Object>> pageQuery) {
        Pagination pagination = new Pagination(pageQuery.getCurrent(), pageQuery.getSize());
        Map<String, Object> param = Maps.newHashMap();
        List<Map<String, Object>> userList = this.sysAppMapper.querySysAppPage(pagination, param);
        userList.parallelStream().forEach(s -> {
            String temp = Objects.toString(s.get("authorizedGrantTypes"));
            s.put("authorizedGrantTypes", Arrays.asList(temp.split(",")));
        });
        log.info("suserList:{}", userList);
        pageQuery.setRecords(userList);
        pageQuery.setTotal(pagination.getTotal());
        return pageQuery;
    }

    @Override
    public void saveOrUpdate(SysAppDto dto) {
        SysApp sysApp = new SysApp();
        BeanUtils.copyProperties(dto, sysApp);
        OauthClientDetails oauthClientDetails = new OauthClientDetails();
        log.info("插入应用开始-------------");
        log.info("dto:{}", dto);
        if (dto.getAppId() != null) {
            log.info("更新应用开始-------------");
            SysApp app = sysAppRepository.findById(dto.getAppId().toString()).orElseThrow(() -> new ApplicationException("不存在该app应用"));
            OauthClientDetails details = oauthClientDetailsRepository.findByClientId(app.getClientId());
            oauthClientDetailsRepository.deleteByClientId(app.getClientId());
            details.setClientId(dto.getClientId());
            details.setWebServerRedirectUri(dto.getWebServerRedirectUri());
            //生成密钥
            details.setClientSecret(dto.getClientSecret());
            // 设置资源id 和授权模式
            details.setResourceIds(dto.getResource());
            details.setAuthorizedGrantTypes(dto.getAuthorizedGrantTypes());
            log.info("应用-------------details:{}", details);
            sysAppRepository.updateIgnoreNull(sysApp);
            oauthClientDetailsRepository.insert(details);
            return;
        }
        sysAppRepository.insert(sysApp);
        oauthClientDetails.setClientId(dto.getClientId());
 //       oauthClientDetails.setScope("read");
        oauthClientDetails.setAuthorities("ROLE_ADMIN");
        // 设置资源id 和授权模式
        oauthClientDetails.setResourceIds(dto.getResource());
        oauthClientDetails.setAuthorizedGrantTypes(dto.getAuthorizedGrantTypes());
        oauthClientDetails.setAutoapprove("true");
        oauthClientDetails.setSecret(dto.getSecret());
        //生成密钥
        oauthClientDetails.setClientSecret(dto.getClientSecret());
       oauthClientDetails.setWebServerRedirectUri(dto.getWebServerRedirectUri());
        log.info("插入应用结束-------------oauthClientDetails:{}", oauthClientDetails);
        oauthClientDetailsRepository.insert(oauthClientDetails);
    }

    @Override
    public void deleteSysApp(String clientId) {
        SysApp sysApp = sysAppRepository.findByClientIdOrderByAppIdDesc(clientId);
        log.info("sysApp:{}", sysApp);
        sysAppRepository.deleteByClientId(clientId);
        oauthClientDetailsRepository.deleteByClientId(sysApp.getClientId());
    }


    @Override
    public List<Map<String, Object>> querySysApps(Integer appType, Long projectId) {
        List<Map<String, Object>> appList = this.sysAppMapper.querySysApps(appType, projectId);
        log.info("appList:{}", appList);
        return appList;
    }
}
